package com.example.yorkfeng.musicdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    public static SharedPreferences mSharePre;
    private ImageView albumImage;
    private TextView musicInfo, musicTitle, tvCur, tvTotal, tvLoop;
    private Button mPrevious,mPlay,mPause,mNext, btnLoop;
    private SeekBar seekVol, seekPro;
    private int loopMode;
    private ListView lvSongs;
    private List<MusicInfo> musicList;
    private ComponentName component;

    private MusicServiceReceiver MusicServiceReceiver;
    private MyVolumeReceiver mVolumeReceiver;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSharePre = getSharedPreferences("mSharePre_MusicDemo", 0);

        //载入视图
        setupViews();

        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
        int current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        seekVol.setProgress(current);
        seekVol.setMax(max);

        Intent mIntent = new Intent(MusicService.INIT_ACTION);
        mIntent.putExtra("position", mSharePre.getInt("mMusicPlayPosition", 0));
        mIntent.setComponent(component);
        startService(mIntent);

        mIntent = new Intent(MusicService.LIST_ACTION);
        mIntent.setComponent(component);
        startService(mIntent);

        loopMode = mSharePre.getInt("mMusicPlayMode", 0);
        mIntent = new Intent(MusicService.MODE_ACTION);
        mIntent.setComponent(component);
        mIntent.putExtra("mode", loopMode);
        startService(mIntent);

        switch (loopMode) {
            case 0:
                tvLoop.setText("全部循环");
                break;

            case 1:
                tvLoop.setText("单曲循环");
                break;

            case 2:
                tvLoop.setText("随机播放");
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播接收器
        registerReceiver();

        Intent mIntent = new Intent(MusicService.UPDATE_ACTION);
        mIntent.setComponent(component);
        startService(mIntent);
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(MusicServiceReceiver);
        unregisterReceiver(mVolumeReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Intent mIntent = new Intent(MusicService.CLOSE_ACTION);
        mIntent.setComponent(component);
        startService(mIntent);
    }

    //初始化一些工作
    public void setupViews(){
        component = new ComponentName(this,
                MusicService.class);

        mPrevious = (Button)findViewById(R.id.btn_music_previous);
        mPlay = (Button)findViewById(R.id.btn_music_play);
        mPause = (Button)findViewById(R.id.btn_music_pause);
        mNext = (Button)findViewById(R.id.btn_music_next);
        btnLoop = (Button)findViewById(R.id.btn_music_btnLoop);
        seekVol = (SeekBar)findViewById(R.id.seek_music_Vol);
        seekPro = (SeekBar)findViewById(R.id.seek_music_Pro);

        mPrevious.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mPause.setOnClickListener(this);
        mNext.setOnClickListener(this);
        btnLoop.setOnClickListener(this);
        seekVol.setOnSeekBarChangeListener(this);
        seekPro.setOnSeekBarChangeListener(this);

        albumImage = (ImageView) findViewById(R.id.img_music_Album);
        albumImage.setImageResource(R.mipmap.img_music);

        musicInfo = (TextView) findViewById(R.id.tv_music_Info);
        musicTitle = (TextView) findViewById(R.id.tv_music_Title);
        tvCur = (TextView) findViewById(R.id.tv_music_Cur);
        tvTotal = (TextView) findViewById(R.id.tv_music_Total);
        tvLoop = (TextView) findViewById(R.id.tv_music_loop);

        lvSongs = (ListView) findViewById(R.id.lv_Music);
    }
    //按钮点击事件响应
    public void onClick(View v) {
        if(v == mPrevious){
            Intent mIntent = new Intent(MusicService.PREVIOUS_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == mPlay){
            Intent mIntent = new Intent(MusicService.PLAY_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == mPause){
            Intent mIntent = new Intent(MusicService.PAUSE_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == mNext){
            Intent mIntent = new Intent(MusicService.NEXT_ACTION);
            mIntent.setComponent(component);
            startService(mIntent);
        }else if(v == btnLoop){
            loopMode = (loopMode+1)%3;
            SharedPreferences.Editor mEditor = MainActivity.mSharePre.edit();
            mEditor.putInt("mMusicPlayMode", loopMode);
            mEditor.commit();

            Intent mIntent = new Intent(MusicService.MODE_ACTION);
            mIntent.setComponent(component);
            mIntent.putExtra("mode", loopMode);
            startService(mIntent);

            System.out.println(loopMode);

            switch (loopMode) {
                case 0:
                    tvLoop.setText("全部循环");
                    break;

                case 1:
                    tvLoop.setText("单曲循环");
                    break;

                case 2:
                    tvLoop.setText("随机播放");
                    break;

                default:
                    break;
            }
        }

    }

    private void registerReceiver(){
        MusicServiceReceiver = new MusicServiceReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MusicService.ACTION_UPDATE_PROGRESS);
        intentFilter.addAction(MusicService.ACTION_UPDATE_DURATION);
        intentFilter.addAction(MusicService.ACTION_UPDATE_INFO);
        intentFilter.addAction(MusicService.ACTION_UPDATE_LIST);
        registerReceiver(MusicServiceReceiver, intentFilter);

        mVolumeReceiver = new MyVolumeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(mVolumeReceiver, filter);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.seek_music_Pro:
                Intent mIntent = new Intent(MusicService.SEEK_ACTION);
                mIntent.setComponent(component);
                mIntent.putExtra("position", seekBar.getProgress());
                startService(mIntent);
                break;

            case R.id.seek_music_Vol:
                AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), 0);
                break;

            default:
                break;
        }
    }

    /**
     * 处理音量变化时的界面显示
     * @author long
     */
    private class MyVolumeReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //如果音量发生变化则更改seekbar的位置
            if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
                AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
                int current = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

                seekVol.setProgress(current);
                seekVol.setMax(max);
            }
        }
    }

    class MusicServiceReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(MusicService.ACTION_UPDATE_PROGRESS.equals(action)){
                int progress = intent.getIntExtra(MusicService.ACTION_UPDATE_PROGRESS, 0);

                if(progress > 0){
                    seekPro.setProgress(progress / 1000);

                    int hour = progress/1000/3600;
                    int min = progress/1000/60;
                    int sec = progress/1000%60;
                    String time = (hour > 0 ? hour + ":" : "") +
                            (min >= 10 ? min : "0" + min) + ":" + (sec >= 10 ? sec : "0" + sec);
                    tvCur.setText(time);
                }

            }else if(MusicService.ACTION_UPDATE_DURATION.equals(action)){
                String tmp = intent.getStringExtra(MusicService.ACTION_UPDATE_DURATION);
                int max = Integer.valueOf(tmp).intValue();
                seekPro.setMax(max / 1000);

                int hour = max/1000/3600;
                int min = max/1000/60;
                int sec = max/1000%60;
                String time = (hour > 0 ? hour + ":" : "") +
                        (min >= 10 ? min : "0" + min) + ":" + (sec >= 10 ? sec : "0" + sec);
                tvTotal.setText(time);

            }else if(MusicService.ACTION_UPDATE_INFO.equals(action)){
                String title = intent.getStringExtra("title");
                String info = intent.getStringExtra("info");
                String albumArt = intent.getStringExtra("albumArt");

                musicInfo.setText(info);
                musicTitle.setText(title);

                Bitmap bm = null;
                if (albumArt == null) {
                    albumImage.setImageResource(R.mipmap.img_music);
                } else {
                    bm = BitmapFactory.decodeFile(albumArt);
                    BitmapDrawable bmpDraw = new BitmapDrawable(bm);
                    albumImage.setImageDrawable(bmpDraw);
                }

            }else if(MusicService.ACTION_UPDATE_LIST.equals(action)){
                musicList =  (List<MusicInfo>) intent.getSerializableExtra(MusicService.ACTION_UPDATE_LIST);

                MusicAdapter adapter = new MusicAdapter();
                lvSongs.setAdapter(adapter);
                lvSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Intent mIntent = new Intent(MusicService.CHANGE_ACTION);
                        mIntent.setComponent(component);
                        mIntent.putExtra("position", position);
                        startService(mIntent);
                    }
                });
            }
        }

    }

    class MusicAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return musicList.size();
        }

        @Override
        public Object getItem(int position) {
            return musicList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return musicList.get(position).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if(convertView == null){
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.music_item, null);
                ImageView pImageView = (ImageView) convertView.findViewById(R.id.img_music_albumPhoto);
                TextView pTitle = (TextView) convertView.findViewById(R.id.tv_music_title);
                TextView pDuration = (TextView) convertView.findViewById(R.id.tv_music_duration);
                TextView pArtist = (TextView) convertView.findViewById(R.id.tv_music_artist);
                viewHolder = new ViewHolder(pImageView, pTitle, pDuration, pArtist);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.title.setText(musicList.get(position).getTitle());
            viewHolder.artist.setText(musicList.get(position).getArtist());

            int duration = musicList.get(position).getDuration();
            int hour = duration/1000/3600;
            int min = duration/1000/60;
            int sec = duration/1000%60;
            String time = (hour > 0 ? hour + ":" : "") +
                    (min >= 10 ? min : "0" + min) + ":" + (sec >= 10 ? sec : "0" + sec);
            viewHolder.duration.setText(time);

            String albumArt = musicList.get(position).getAlbumArt();
            Bitmap bm = null;
            if (albumArt == null) {
                viewHolder.imageView.setImageResource(R.mipmap.img_music);
            } else {
                bm = BitmapFactory.decodeFile(albumArt);
                BitmapDrawable bmpDraw = new BitmapDrawable(bm);
                viewHolder.imageView.setImageDrawable(bmpDraw);
            }

            return convertView;
        }
    }

    class ViewHolder{
        public ViewHolder(ImageView pImageView, TextView pTitle, TextView pDuration, TextView pArtist){
            imageView = pImageView;
            title = pTitle;
            duration = pDuration;
            artist = pArtist;
        }

        ImageView imageView;
        TextView title;
        TextView duration;
        TextView artist;
    }
}
